import os
import subprocess
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

def should_update():
    return os.getenv("AUTO_UPDATE_ENABLED", "false").lower() == "true"

def run(cmd, cwd=None):
    subprocess.run(cmd, cwd=cwd, check=True)

def git_update(repo_dir: str, branch: str):
    run(["git", "fetch", "origin", branch], cwd=repo_dir)
    run(["git", "reset", "--hard", f"origin/{branch}"], cwd=repo_dir)

def run_compose():
    compose_path = os.getenv("COMPOSE_FILE_PATH", "/workspace/docker-compose.yml")
    run(["docker-compose", "-f", compose_path, "build"])
    run(["docker-compose", "-f", compose_path, "up", "-d"])

def verify_signature(secret: str, request: Request, payload: bytes):
    token = request.headers.get("X-Gitee-Token", "")
    return secret and token and token == secret

@app.post("/hooks/gitee")
async def gitee_hook(request: Request):
    secret = os.getenv("GITEE_WEBHOOK_SECRET", "")
    body = await request.body()
    if not verify_signature(secret, request, body):
        raise HTTPException(status_code=401, detail="unauthorized")
    if not should_update():
        return {"status": "skipped"}
    repo_dir = os.getenv("REPO_DIR", "/workspace")
    branch = os.getenv("GIT_BRANCH", "main")
    git_update(repo_dir, branch)
    run_compose()
    return {"status": "updated"}
